<template>
    <div id="app">
        姓名<el-input v-model="studentName" placeholder="姓名" style="width: 150px;"></el-input>
        手机号<el-input v-model="phoneNumber" placeholder="手机号" style="width: 150px;"></el-input>
        班级名称<el-input v-model="className" placeholder="班级名称" style="width: 150px;"></el-input>
        修改照片时间
            <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker>
            <el-button class="an sous" @click="get"><i class="el-icon-search"></i> 搜索</el-button>
            <el-button class="chongz" @click="reset"><i class="el-icon-refresh"></i> 重置</el-button><br>
            <br>
            <el-button class="an"><router-link to="/addStudent" style="color: white;text-decoration: none!important;"><i class="el-icon-plus"></i> 新增学员</router-link></el-button>
            <el-button type="primary" @click="openUploadDialog" class="an" style="width:130px;background-color: #13ce66;"><i class="el-icon-upload2"></i> 导入学生信息</el-button>
            <el-button type="primary" @click="openUploadPhotoDialog" class="an" style="width:130px;background-color: #13ce66;"><i class="el-icon-upload2"></i> 导入学生照片</el-button>
            <el-button type="primary" @click="deriveStuInfo" class="an" style="width:100px;background-color: #ffc731;"><i class="el-icon-download"></i> 学员导出</el-button>
            <div>
                <!-- 上传文件的弹窗 -->
                <el-dialog title="导入学生信息" :visible.sync="uploadDialogVisible" width="40%">

                    <!-- 文件上传 -->
                    <el-upload action="/sys/student/uploadStuInfo" :on-success="handleSuccess" :before-upload="beforeUpload"
                        :on-error="handleError" :limit="1" accept=".xls,.xlsx" drag>
                        <div slot="tip" class="el-upload__tip">将文件拖到此处，或点击上传</div>
                        <span>{{uploadError}}</span>
                    </el-upload>

                    <!-- 下载模版链接 -->
                    <div style="margin-top: 20px;">
                        <el-link type="primary" @click="downloadMo">模版下载</el-link>
                    </div>

                    <!-- 弹窗的底部操作 -->
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="uploadDialogVisible = false">关闭</el-button>
                    </span>
                    
                </el-dialog>
            </div>
            <div>
                <el-dialog title="导入学生照片" :visible.sync="openUploadPhoto" width="40%">

                    <!-- 文件上传 -->
                    <el-upload action="/sys/student/uploadStudentPicture" :on-success="zipHandleSuccess" :before-upload="zipBeforeUpload"
                        :on-error="zipHandleError" :limit="1" accept=".zip" ref="upload" drag>

                        <!-- 增加文件格式验证提示 -->
                        <div slot="tip" class="el-upload__tip">
                            将.zip压缩包文件拖到此处，或点击上传
                        </div>

                        <span>{{zipUploadError}}</span>
                    </el-upload>

                    <!-- 下载模版链接 -->
                    <!-- <div style="margin-top: 20px;">
                        <el-link type="primary" @click="downloadTemplate">模版下载</el-link>
                    </div> -->

                    <!-- 弹窗的底部操作 -->
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="openUploadPhotoA">关闭</el-button>
                    </span>

                </el-dialog>
            </div>
            
            <br>
            <el-table :data="studentList" style="width: 100%">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column fixed prop="studentId" label="学生id" width="100">
                    <template slot-scope="scope">{{ scope.row.studentId }}</template>
                </el-table-column>
                <el-table-column fixed prop="studentName" label="姓名" width="100">
                    
                    <template slot-scope="scope"><span style="color: blue;"
                        @click="goToStudentPage(scope.row)"><i class="el-icon-edit">{{ scope.row.studentName }}</i></span></template>
                </el-table-column>
                <el-table-column fixed prop="phoneNumber" label="学生手机号" width="130">
                    <template slot-scope="scope">{{ scope.row.phoneNumber }}</template>
                </el-table-column>
                <el-table-column fixed prop="guardianPhone" label="家长手机号" width="130">
                    <template slot-scope="scope">{{ scope.row.guardianPhone }}</template>
                </el-table-column>
                <el-table-column fixed prop="className" label="班级" width="100">
                    <template slot-scope="scope">{{ scope.row.className }}</template>
                </el-table-column>
                <el-table-column prop="dormitoryId" label="走读/住宿" width="110">
                    <template slot-scope="scope">{{ scope.row.hostelId === 32? '走读' : scope.row.levelName }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">{{ scope.row.status == 1? '有效':'无效' }}</template>
                </el-table-column>
                <el-table-column prop="" label="启/停用" width="100">
                    <template></template>
                </el-table-column>
                <el-table-column prop="" label="微信公众号" width="120">
                    <template></template>
                </el-table-column>
                <el-table-column prop="sex" label="性别" width="100">
                    <template slot-scope="scope">{{ scope.row.sex ==1? '男':'女' }}</template>
                </el-table-column>
                <el-table-column prop="documentName" label="证件类型" width="150">
                    <template slot-scope="scope">{{ scope.row.documentName }}</template>
                </el-table-column>
                <el-table-column prop="documentNumber" label="证件号" width="200">
                    <template slot-scope="scope">{{ scope.row.documentNumber }}</template>
                </el-table-column>
                <el-table-column prop="nativePlace" label="籍贯" width="100">
                    <template slot-scope="scope">{{ scope.row.nativePlace }}</template>
                </el-table-column>
                <el-table-column prop="nation" label="民族" width="100">
                    <template slot-scope="scope">{{ scope.row.nation }}</template>
                </el-table-column>
                <el-table-column prop="politicalName" label="政治面貌" width="150">
                    <template slot-scope="scope">{{ scope.row.politicalName }}</template>
                </el-table-column>
                <el-table-column prop="enrollmentDate" label="入学年月" width="150">
                    <template slot-scope="scope">{{ scope.row.enrollmentDate }}</template>
                </el-table-column>
                <el-table-column prop="createName" label="创建用户" width="100">
                    <template slot-scope="scope">{{ scope.row.createName }}</template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="130">
                <template slot-scope="scope">
                    <el-button  @click.native="showHostelaaa(scope.row)" type="text" size="small">宿舍分配</el-button>
                    <el-button type="text" size="small" @click.native="delStudentBed(scope.row)" v-if="scope.row.hostelId !== 32">退宿</el-button>
                    <el-button type="text" size="small" @click.native="delStudent(scope.row)">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 30px;margin-left: 1150px;" v-if="pageCount>=1">
                <el-button-group>
                    <el-button type="primary" icon="el-icon-arrow-left" @click="prevPage">上一页</el-button>
                    <el-button><span>{{pageNum}} / {{pageCount}}</span></el-button>
                    <el-button type="primary" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                </el-button-group>
            </div>
            <el-row v-if="showHostel">
                <el-dialog title="宿舍分配" :visible.sync="showHostel" width="30%">
                    <el-col :span="24" style="margin-left: 30px;">
                        <span style="font-weight: bold">姓名 </span>{{this.student.studentName}}
                        <span style="font-weight: bold">班级 </span>{{this.student.className}}
                        <span style="font-weight: bold">当前宿舍 </span>{{ this.student.hostelId === 32? '走读' : this.student.levelName }}
                        <p></p>
                        
                    </el-col>
                    
                    <label style="font-weight: bold">选择宿舍&nbsp;</label>
                    <el-select v-model="selectedHostel" @click.native="sysHostelList" @change="getSysHostelAll">
                        <el-option v-for="sysHostel in sysHostelAll" :key="sysHostel.id" :label="sysHostel.levelName"
                            :value="sysHostel.id"></el-option>
                    </el-select>
                    <el-select v-model="selectedBed" @click.native="getBedByHostelId(selectedHostel)">
                        <el-option v-for="bed in bedList" :key="bed.id" :label="`${bed.bedNumber}号床`"
                            :value="bed.id">
                                    <!-- <template slot-scope="scope">{{ scope.row.bedNumber }}</template> -->
                        </el-option>
                    </el-select>
                        <span slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="addHostel">确 定</el-button>
                        <el-button @click="showHostel = false">取 消</el-button>
                    </span> 
                </el-dialog>
            </el-row>
        </div>
</template>
<script>
    import axios from 'axios';
    export default {
        name: 'StudentManagement',
        data() {
            return {
                pageCount:'',
                pageNum:1,
                value1: '',
                studentList:[],
                studentName:'',
                className:'',
                phoneNumber:'',
                showHostel:false,
                student:{},
                sysHostelAll:[],
                selectedHostel:'',
                selectedBed:'',
                hostelId:'',
                bedList:[],
                uploadDialogVisible: false,
                uploadError:'',
                openUploadPhoto:false,
                zipUploadError:'',
            }
        },
        created () {
            this.getSysStudentList(1);
        },
        methods: {
            delStudent(row){
                this.student = row;
                    if(confirm("确定删除"+this.student.studentName+"学生信息?")){
                        axios({
                        url: 'http://localhost:9002/sys/student/delStuById',
                        method: 'post',
                        params: {
                            id: row.id,
                            studentId:this.student.studentId,
                            hostelId:this.student.hostelId
                        },
                        headers: {
                            'Authorization': this.Authorization
                        }
                    }).then(response => {
                        console.log(response);
                        if(response.data.status == 200){
                            this.getSysStudentList(1);
                        }else{
                            alert("删除失败");
                        }
                    })
                }
                
            },
            addHostel(){
                this.selectedBed;
                this.selectedHostel;
                this.student.id;
                console.log("学号："+this.student.studentId);
                console.log("宿舍id："+this.selectedHostel);
                console.log("床位id："+this.selectedBed);
                axios({
                    url: 'http://localhost:9002/sys/bed/addHostelByStuId',
                    method: 'post',
                    params: {
                        studentId: this.student.studentId,
                        hostelId: this.selectedHostel,
                        id: this.selectedBed
                    },
                    headers: {
                        'Authorization': this.Authorization
                    }
                }).then(response => {
                    console.log(response);
                    if(response.data.status == 200){
                        this.getSysStudentList(1);
                        this.showHostel = false;
                    }else{
                        alert(response.data.msg);
                    }
                    
                })
            },
            delStudentBed(row){
                this.student = row;
                this.Authorization = localStorage.getItem("Authorization");
                axios({
                    url: 'http://localhost:9002/sys/bed/delStuBedById',
                    method: 'post',
                    params: {
                        id: row.id,
                        studentId:this.student.studentId,
                        hostelId:this.student.hostelId
                    },
                    headers: {
                        'Authorization': this.Authorization
                    }
                }).then(response => {
                    console.log(response);
                })
            },
            getBedByHostelId(id){
                this.hostelId = id;
                if(id == ''){
                    return;
                }
                console.log("宿舍id："+this.hostelId);
                axios({
                    url: 'http://localhost:9002/sys/bed/getBedByHostelId',
                    method: 'post',
                    params: {
                        id: this.hostelId
                    },
                    headers: {
                        'Authorization': this.Authorization
                    }
                })
                .then(response => {
                    console.log(response);
                    this.bedList = response.data.data;
                })
            },
            sysHostelList(){
                this.Authorization = localStorage.getItem("Authorization");
                axios({
                    url: 'http://localhost:9002/sys/hostel/getSysHostelAll',
                    method: 'post',
                    headers: {
                        'Authorization': this.Authorization
                    }
                })
                .then(response => {
                    console.log(response);
                    this.sysHostelAll = response.data.data;
                })
            },
            showHostelaaa(row){
                this.student = row;
                this.showHostel = true;
            },
            prevPage(){
                this.pageNum--;
                var pageNum = this.pageNum;
                if(this.pageNum >= 1){
                    this.getSysStudentList(pageNum);
                }else{
                    this.getSysStudentList(1);
                }   
            },
            nextPage(){
                this.pageNum++;
                var pageNum = this.pageNum;
                if(this.pageNum <= this.pageCount){
                    this.getSysStudentList(pageNum);
                }else{
                    this.getSysStudentList(this.pageCount);
                }                
            },
            handleClick(row) {
                console.log(row);
            },
            getSysStudentList(pageNum){
                this.pageNum = pageNum;
                this.Authorization = localStorage.getItem("Authorization");
                axios({
                    url: 'http://localhost:9002/sys/student/getSysStudentList',
                    method: 'post',
                    params: {
                        pageNum: this.pageNum,
                        pageSize: 5,
                        studentName:this.studentName,
                        className:this.className,
                        phoneNumber:this.phoneNumber
                    },
                    headers: {
                        'Authorization': this.Authorization
                    }
                })
                .then(response => {
                    console.log(response);
                    this.studentList=null;
                    this.studentList = response.data.data.sysStudentList;
                    this.pageCount = response.data.data.pageCount;
                    console.log(this.studentList);
                })
            },
            get(){
                let pageNum =this.pageNum;
                this.getSysStudentList(pageNum);
            },
            reset(){
                
            },
            goToStudentPage(row) {
                const student = row;
                console.log(student);
                localStorage.setItem("row", row.id);
                // localStorage.setItem("student",student);
            // 根据学生信息进行路由跳转逻辑，这里假设跳转到 /student/:id 路由
                // this.$router.push(`/updStudent`);
                this.$router.push({ name: 'updStudent', params: { student: student } });
            },
             // 上传成功的处理
            handleSuccess(response, file, fileList) {
                console.log(file);
                console.log(fileList);
                if (response.status === 200) {
                    this.$message.success('学生信息上传成功！');
                } else if (response.data.status === 400 && response.data.length) {
                    // 如果有错误信息，逐行提示
                    response.data.forEach((error) => {
                        this.$message.error(error);
                    });
                } else {
                    this.$message.error('上传失败，请重试。');
                }
            },

            
            // 上传错误的处理
            handleError(err, file, fileList) {
                console.error('上传错误:', err);
                console.error('上传错误文件列表:', fileList);
                console.error('上传错误文件信息:', file);
                this.$message.error('上传过程中出现错误，请稍后重试。');
            },
            beforeUpload(file) {
                const formData = new FormData();
                formData.append('file', file);

                axios.post('http://localhost:9002/sys/student/uploadStuInfo', formData, {
                    headers: {
                        'Authorization': localStorage.getItem("Authorization"),
                    }
                }).then(response => {
                    console.log(response);
                    if (response.data.status === 200) {
                        this.$message.success('文件上传成功');
                        // this.showDormitory = false;
                        this.getSysStudentList(1);
                    } else{
                        this.$message.error('上传失败: ' + response.data.msg);
                        this.uploadError=response.data.data;
                    }
                }).catch(error => {
                    this.$message.error('上传错误: ' + error);
                });

                return false; // 阻止 el-upload 默认上传
            },
            downloadMo(){
                //下载模版
                var a = document.createElement("a"); //创建一个<a></a>标签
                a.href = "/static/学生导入模板.xlsx"; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
                a.download = "学生导入模版.xlsx"; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
                a.style.display = "none"; // 障眼法藏起来a标签
                document.body.appendChild(a); // 将a标签追加到文档对象中
                a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
                a.remove(); // 一次性的，用完就删除a标签
            },
            openUploadDialog() {
                this.uploadDialogVisible = true;
            },
            openUploadPhotoDialog(){
              this.openUploadPhoto = true;  
            },
            deriveStuInfo(){
                this.Authorization = localStorage.getItem("Authorization");
                axios({
                    url: 'http://localhost:9002/sys/student/deriveStuInfo',
                    method: 'post',
                    headers: {
                        'Authorization': this.Authorization
                    }
                })
                .then(response => {
                    console.log(response);
                    if(response.data.status == 200){
                        this.$message.success(response.data.msg);
                    }else{
                        this.$message.error(response.data.msg);
                    }
                })
                return false;
            },
           
            
            zipBeforeUpload(file) {
                const formData = new FormData();
                formData.append('file', file);
                this.Authorization = localStorage.getItem("Authorization");
                axios.post('http://localhost:9002/sys/student/uploadStudentPicture', formData, {
                    headers: {
                        'Authorization': this.Authorization
                    }
                })
                .then(response => {
                    console.log(response);
                    if (response.data.status === 200) {
                        this.$message.success('文件上传成功');
                        this.getSysStudentList(1);
                    } else{
                        this.$message.error('上传失败: ' + response.data.msg);
                        this.zipUploadError=response.data.data;
                    }
                }).catch(error => {
                    this.$message.error('上传错误: ' + error);
                });
            },
            zipHandleSuccess(response, file, fileList) {
                console.error('上传错误文件列表:', fileList);
                console.error('上传错误文件信息:', file);
                // 假设服务器端返回的成功信息在response中，这里可以根据具体情况进行处理
                if (response.success) {
                    // 例如，如果需要解压上传成功的.zip文件，可以在这里调用相关解压函数（假设已经存在）
                    this.unzipFile(response.filePath); 
                }
            },
            zipHandleError(err, file, fileList) {
                console.error('上传错误文件列表:', fileList);
                console.error('上传错误文件信息:', file);
                console.error('上传错误:', err);
                // this.zipUploadError = '上传.zip压缩包时出现错误：' + err.message;
            },
            openUploadPhotoA(){
                this.zipUploadError = '';
                this.openUploadPhoto = false;
            }
        },

    }
</script>
<style>
.an{
    background-color: #1890ff;color: white;font-size: 13px;width: 80px;height: 30px;text-align: center;padding-left: 5px;
    padding-right: 5px;padding-top: 8px;
}
.sous{
    margin-left: 20px;
}
.chongz{
    font-size: 13px;width: 80px;height: 30px;text-align: center;padding-left: 5px;
    padding-right: 5px;padding-top: 8px;
    margin-left: 20px;
}
.checkbox-with-space::after {
     content: "    ";
     white-space: pre;
   }
</style>